package com.xiaoxiong.newmyscse.net;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.cookie.Cookie;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;

import android.annotation.SuppressLint;
import android.os.Handler;
import android.os.Message;
import android.util.Log;

import com.xiaoxiong.newmyscse.bean.ResultData;
import com.xiaoxiong.newmyscse.intef.ResultInterface;

/**
 * 
 * @ClassName: MyHttpPost 
 * @Description: 网络请求类
 * @author smile
 * @date 2016年5月17日 上午1:35:36 
 *
 */
public class MyHttpPost {
	private final static int SUCCESS = 1;// 请求成功
	private final static int FAILE = 0;// 请求失败
	private boolean isNeedGetCookies;// 是否需要获取cookies
	private Map<String, String> postParams;// 提交的参数，例如学号、密码等
	private String postUrl;// 请求的地址
	private ResultInterface which;// 代表在那里调用这个方法请求的，请求完成会返回数据给它

	public MyHttpPost(ResultInterface which) {
		super();
		this.which = which;
		this.isNeedGetCookies = false;
		this.postParams = new HashMap<String, String>();
		this.postUrl = "";
	}

	public MyHttpPost(ResultInterface which, String postUrl,
			Map<String, String> postParams, boolean isNeedGetCookies) {
		super();
		this.which = which;
		this.isNeedGetCookies = isNeedGetCookies;
		this.postParams = postParams;
		this.postUrl = postUrl;
	}

	public void setNeedGetCookies(boolean isNeedGetCookies) {
		this.isNeedGetCookies = isNeedGetCookies;
	}

	public void setPostParams(Map<String, String> postParams) {
		this.postParams = postParams;
	}

	public void setPostUrl(String postUrl) {
		this.postUrl = postUrl;
	}

	/**
	 * 
	* @Title: post 
	* @Description: 开始请求
	* @param 
	* @return void
	* @throws
	 */
	public void post() {
		new Thread(new Runnable() {

			@Override
			public void run() {
				try {
					// 创建DefaultHttpClient对象
					DefaultHttpClient httpClient = new DefaultHttpClient();

					// 创建HttpPost对象并设置请求地址
					HttpPost httpPost = new HttpPost(postUrl);

					// 保存参数
					List<NameValuePair> params = new ArrayList<NameValuePair>();
					for (String key : postParams.keySet()) {
						params.add(new BasicNameValuePair(key, postParams
								.get(key)));
					}

					// 设置参数和编码
					UrlEncodedFormEntity urlEncodedFormEntity = new UrlEncodedFormEntity(
							params, "utf-8");
					httpPost.setEntity(urlEncodedFormEntity);
					// 调用execute方法发送请求
					HttpResponse httpResponse = httpClient.execute(httpPost);
					// 取出请求返回的状态码，200代表请求成功
					if (httpResponse.getStatusLine().getStatusCode() == 200) {
						// 调用getEntity()方法获取HttpEntity实例并转换成字符串
						HttpEntity entity = httpResponse.getEntity();
						String response = EntityUtils.toString(entity, "utf-8");

						String cookieName = "";
						String cookieValue = "";
						// 如果需要获取cookie，获取cookie并保存
						if (isNeedGetCookies) {
							List<Cookie> cookies = httpClient.getCookieStore()
									.getCookies();
							cookieName = cookies.get(0).getName();
							cookieValue = cookies.get(0).getValue();
						}

						// 发送消息，包含cookie名跟值、请求得到的内容
						Message message = new Message();
						message.what = SUCCESS;
						
						ResultData resultData = new ResultData(true, cookieName, cookieValue, response);
						message.obj = resultData;
						
						mHandler.sendMessage(message);
					} else {
						Message message = new Message();
						message.what = FAILE;
						message.obj = "请求失败";
						mHandler.sendMessage(message);
					}
					// 请求结束，使用连接管理器关闭 httpClient
					httpClient.getConnectionManager().shutdown();
				} catch (Exception e) {
					Message message = new Message();
					message.what = FAILE;
					message.obj = "请求失败";
					mHandler.sendMessage(message);
					e.printStackTrace();
				}
			}

		}).start();
	}

	@SuppressLint("HandlerLeak")
	private Handler mHandler = new Handler() {
		public void handleMessage(Message msg) {
			switch (msg.what) {
			case SUCCESS:
				Log.d("status", "success");
				// 请求成功，把数据发送回去
				which.resultOfPost((ResultData)msg.obj);

				break;
			case FAILE:
				Log.d("status", "fail");
				// 请求失败，发送失败标志就可以了
				ResultData failData = new ResultData(false);
				which.resultOfPost(failData);

				break;
			}
		};
	};

}
